//
//  SXPEmoticonView.swift
//  weibo
//
//  Created by shixinPeng on 16/3/8.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
/*
上部分为colletionview
下部分为uiview 四个按钮
先添加上部的uicollectionview
表情上屏后要做的就是
1.添加删除按钮,按钮填完
2.实现上下联动
5.实现最近
3.实现点击上图
6,实现插入
7.实现发送文本的转换
4.实现删除
1.emoji的发表
--
下一阶段要实现
2.正文的装换
3.数据库
4.代码的抽取

*/

let SXPEmoticonViewCellId = "SXPEmoticonViewCellId"
let SXPaddemoticonNotification = "SXPaddemoticonNotification"
let SXPdeleteEmoticonClick = "SXPdeleteEmoticonClick"

class SXPEmoticonView: UIView,UICollectionViewDataSource,SXPChancelViewDelegate,UICollectionViewDelegate {

    /// 记录当前表情框的索引
    var currentIndexPath:NSIndexPath?
    /// 当前点击的组标
    var preIndex = 0
    

    
    override init(frame: CGRect) {
        super.init(frame: frame)
     
        setupUI()
        setupCollection()
        ///  获取数据
        
        
        //printLog(SXPemoticonManger.getEmoticonData())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //私有方法加载控件
    private func setupUI(){
        addSubview(emoticonColView)
        //emoticonColView.backgroundColor = UIColor.blueColor()
        addSubview(channelView)
        //channelView.backgroundColor = UIColor.redColor()
      
    
        
        //添加约束
        emoticonColView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(channelView.snp_top)
        }
        channelView.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(self.snp_right)
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(self.snp_bottom)
            make.height.equalTo(40)
        }
    }
    //MARK:--设置setup的属性
    private func setupCollection(){
        
        emoticonColView.dataSource = self
        emoticonColView.delegate = self
        self.emoticonColView.registerClass(SXPemticonCell.self, forCellWithReuseIdentifier:SXPEmoticonViewCellId )
        flowlayout.scrollDirection = .Horizontal
        //取消滑块
        emoticonColView.showsHorizontalScrollIndicator = false
        emoticonColView.showsVerticalScrollIndicator = false
        //打开分页
        emoticonColView.pagingEnabled = true
        //取消弹簧效果
        emoticonColView.bounces = false
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        flowlayout.itemSize = CGSizeMake(kUISCREEN_W, emoticonColView.frame.height)
        flowlayout.minimumInteritemSpacing = 0
        flowlayout.minimumLineSpacing = 0
    }
    
    //懒加载上部界面
    private lazy var flowlayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    private lazy var emoticonColView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowlayout)
    //下部界面 标签控件
    private lazy var channelView:SXPChancelView = {
       let toolBar = SXPChancelView()
        
        toolBar.delegate = self
        
        return toolBar
        
    }()
}
//MARK: --collection的数据源方法
extension SXPEmoticonView{
    //返回组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return SXPemoticonManger.getEmoticonData().count
    }
    //返回item数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return SXPemoticonManger.getEmoticonData()[section].count
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SXPEmoticonViewCellId, forIndexPath: indexPath) as! SXPemticonCell
        
       currentIndexPath = indexPath
        cell.model = SXPemoticonManger.getEmoticonData()[indexPath.section][indexPath.row]
        return cell
        
    }
    
    }
//MARK: --collection的代理方法
extension SXPEmoticonView{
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //printLog("\(currentIndexPath?.section)--\(currentIndexPath?.item)")
        //改变底部标签的选中状态.要判断离开了当前的组
        if let index = currentIndexPath?.section {
            if index != preIndex{
                
                channelView.exchangLabel(index)
                
                preIndex = index
            }
            
           // printLog(index)
        }
       
        
    }
}
//MARK: --自定义cell
class SXPemticonCell: UICollectionViewCell {
    //存放按钮的数组
    private lazy var btnArray:[SXPemoticonBtn] = [SXPemoticonBtn]()
    //定义一个属性.接收索引参数
    var index:NSIndexPath?{
        didSet{
            testLabel.text = "第\(self.index?.section ?? 0)组--第\(self.index?.row ?? 0)页"
        }
    }
    //接收图片数组的属性
    var model:[SXPEmoticonModel]?{
        
        didSet{
            //遍历按钮数组
            for (_,button) in btnArray.enumerate(){
                //把图片隐藏打开
                button.hidden = true
            }
            
            for (index,emotion) in model!.enumerate(){
                let btn = btnArray[index]
                btn.emoticon = emotion
                
            }
     
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    private func setupUI(){
        
    contentView.addSubview(testLabel)
        //添加约束
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
        //btn的宽高
        let BtnW = kUISCREEN_W/7
        let BtnH = frame.size.height/3
        
        //添加按钮
        for i in 0...20{
            //添加button
            let btn = SXPemoticonBtn(type: UIButtonType.Custom)
            //列数
            let col = i%7
            //行数
            let row = i/7
            
            //btn.backgroundColor = kRandomColor()
            
            btn.frame = CGRectMake(CGFloat(col) * BtnW, CGFloat(row) * BtnH, BtnW, BtnH)
            
            //给btn添加方法addemoticonz
            btn.addTarget(self, action: "addemoticon:", forControlEvents: .TouchUpInside)
            
            //添加到视图当中
            contentView.addSubview(btn)
            //添加到数组中
            btnArray.append(btn)
        }
        contentView.addSubview(deleteBtn)
        deleteBtn.frame = CGRectMake(6 * BtnW, 2 * BtnH, BtnW, BtnH)
        
        
        
    }
///  添加一个表情
    @objc private func addemoticon(btn:SXPemoticonBtn){
        
        //把选中的按钮添加到界面中
        //使用通知把信息传递到publicView中
        NSNotificationCenter.defaultCenter().postNotificationName(SXPaddemoticonNotification, object: self, userInfo: ["emotiion": btn.emoticon!])
        
        //先实现添加到最近
        SXPemoticonManger.addRecentBtnArray(btn.emoticon!)
        
        
        
        
        
    }
// MARK:删除前一个图片
    @objc private func deleteEmoticonClick(){
        //printLog("删除前面表情")
     //使用通知删除文本
        NSNotificationCenter.defaultCenter().postNotificationName(SXPdeleteEmoticonClick, object: self)
        
        
    }
    //MARK:--cell里面的空间的懒加载
    private lazy var testLabel:UILabel = {
        let lab = UILabel()
        
        return lab
    }()
    private lazy var btn:SXPemoticonBtn = SXPemoticonBtn()
    private lazy var deleteBtn:UIButton = {
       let btn = UIButton(type: UIButtonType.Custom)
        btn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        btn.addTarget(self, action: "deleteEmoticonClick", forControlEvents: .TouchUpInside)
        return btn
    }()
    
}
//MARK: --SXPChangcelView的Delegat方法
extension SXPEmoticonView{
    
    func exchangeEmotionView(tag: Int) {
        switch tag {
        case 1000:
            let indexPath = NSIndexPath(forItem: 0, inSection: 0)
            self.emoticonColView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            preIndex = 0
            
        case 1001:
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.emoticonColView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            preIndex = 1
        case 1002:
            let indexPath = NSIndexPath(forItem: 0, inSection: 2)
            self.emoticonColView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            
            preIndex = 2
        case 1003:
            let indexPath = NSIndexPath(forItem: 0, inSection: 3)
            self.emoticonColView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
            preIndex = 3
            
        default: break
        }
    }
    
}



















